clear; clc;

%% === Step 1: 加载数据和参数 ===
load('data\YaleB_500.mat');  % 包含：Train_DAT, Test_DAT, trainlabels, testlabels, lambda, w

% 检查变量存在
if ~exist('lambda', 'var'), lambda = 0.1; end
if ~exist('w', 'var'), w = 0.05; end

% 转换变量名
train_data = Train_DAT;       % size: [500 x 760]
test_data = Test_DAT;         % size: [500 x 1968]
train_labels = trainlabels;   % size: [1 x 760]
test_labels = testlabels;

% 获取类别信息
classes = unique(train_labels);
K = length(classes);
[m, ~] = size(train_data);
atoms_per_class = 10;

%% === Step 2: 构建子字典 Di 并计算训练稀疏系数 Z_i
D_list = cell(K, 1);
Z_tilde_list = cell(K, 1);
D_all = [];

for i = 1:K
    % 当前类别的训练样本
    Ai = train_data(:, train_labels == classes(i));

    % 子字典初始化（可替换为 KSVD）
    [U, ~, ~] = svds(Ai, atoms_per_class);
    Di = normc(U);
    D_list{i} = Di;
    D_all = [D_all, Di];

    % 使用 lasso 对每个样本稀疏编码
    n_samples = size(Ai, 2);
    Z_i = zeros(size(Di, 2), n_samples);
    for jj = 1:n_samples
        yj = Ai(:, jj);
        z = lasso(Di, yj, 'Lambda', lambda, 'Standardize', false);
        Z_i(:, jj) = z;
    end
    Z_tilde_list{i} = Z_i;
end

%% === Step 3: 测试样本分类
n_test = size(test_data, 2);
pred_labels = zeros(1, n_test);

for j = 1:n_test
    y = test_data(:, j);
    pred = scsdl_classify(y, D_all, D_list, Z_tilde_list, lambda, w);
    pred_labels(j) = classes(pred);
end

%% === Step 4: 输出分类准确率
acc = mean(pred_labels == test_labels);
fprintf('SCSDL 分类准确率：%.2f%%\n', acc * 100);